package shark.flow.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.flowable.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import shark.common.model.Result;
import shark.flow.service.IFlowProcessInstanceService;
import shark.flow.vo.ProcessInstanceQueryVo;
import shark.flow.vo.ProcessInstanceVo;
import shark.flow.vo.StartProcessInstanceVo;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Base64;

@RestController
@RequestMapping("/instance")
public class FlowInstanceController {

    @Autowired
    private IFlowProcessInstanceService instanceService;

    @PostMapping("/start")
    public Result<ProcessInstanceVo> startProcessInstanceByParam(@RequestBody StartProcessInstanceVo processInstanceVo) {
        ProcessInstance processInstance = instanceService.startProcessInstanceByKey(processInstanceVo);
        ProcessInstanceVo vo = new ProcessInstanceVo(processInstance);
        return new Result<>(200, "success", vo);
    }

    @PostMapping("/myInstance")
    public Result<IPage<ProcessInstanceVo>> getMyProcessInstances(@RequestBody ProcessInstanceQueryVo queryVo) {
        IPage<ProcessInstanceVo> page = instanceService.getInstancePage(queryVo);
        Result<IPage<ProcessInstanceVo>> result = new Result<>(200, "success", page);
        return result;
    }

    @GetMapping("/image/{instanceId}")
    public String getImage(@PathVariable("instanceId") String instanceId) throws IOException {
        byte[] bytes = instanceService.createImage(instanceId);
        String base64 = Base64.getEncoder().encodeToString(bytes);
        return base64;
    }

}
